package com.ztesoft.zsmart.zcm.monitor.config;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.quartz.Scheduler;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * 定时任务配置
 *
 */
@Configuration
public class SchedulerConfiguration {

    @Resource(name = "nmsDataSource")
    private DataSource dataSource;

    /**
     * 通过SchedulerFactoryBean获取Scheduler的实例
     * @return Scheduler
     * @throws Exception
     */
    @Bean
    public Scheduler scheduler() throws IOException {

        return schedulerFactoryBean().getScheduler();

    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {

        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setQuartzProperties(quartzProperties());
        factory.setDataSource(dataSource);
        factory.setApplicationContextSchedulerContextKey("applicationContext");
        factory.setTaskExecutor(schedulerThreadPool());
        factory.setOverwriteExistingJobs(true);
        factory.setAutoStartup(false); // 强制不自动启动
        return factory;

    }

    /**
     * 从配置文件获取quartz配置
     * @return Properties
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/config/quartz.properties"));

        // 在quartz.properties中的属性被读取并注入后再初始化对象
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    @Bean
    public Executor schedulerThreadPool() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(15);
        executor.setMaxPoolSize(25);
        executor.setQueueCapacity(100);

        return executor;

    }
}
